package com.gpj.security.controller;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @className LoginController
 * @description
 *   TODO
 * @author GPJ
 * @date 2023/11/7 22:17
 * @version 1.0
 **/
@RestController
public class LoginController {
	@RequestMapping(value = "/permit")
	public String permit(){
		return "无登录认证接口请求成功";
	}

	@RequestMapping(value = "/login-success")
	public String loginSuccess(@RequestParam String url){
		System.out.println("url:" + url);
		//提示具体用户名称登录成功
		return getUsername()+" 登录成功";
	}

	/**
	 * 测试资源1
	 * @return
	 */
	@GetMapping(value = "/r/r1",produces = {"text/plain;charset=UTF-8"})
	@PreAuthorize("hasAuthority('p1')")//拥有p1权限才可以访问
	public String r1(){
		return getUsername()+" 访问资源1";
	}

	/**
	 * 测试资源2
	 * @return
	 */
	@GetMapping(value = "/r/r2",produces = {"text/plain;charset=UTF-8"})
	@PreAuthorize("hasAuthority('p2')")//拥有p2权限才可以访问
	public String r2(){
		return getUsername()+" 访问资源2";
	}

	//获取当前用户信息
	private String getUsername(){
		String username = null;
		//当前认证通过的用户身份
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		//用户身份
		Object principal = authentication.getPrincipal();
		if(principal == null){
			username = "匿名";
		}
		if(principal instanceof org.springframework.security.core.userdetails.UserDetails){
			UserDetails userDetails = (UserDetails) principal;
			username = userDetails.getUsername();
		}else{
			username = principal.toString();
		}
		return username;
	}
}
